package com.aco.party.web.controller.system;

import com.aco.party.enums.PostTypeEnum;
import com.aco.party.enums.PostsStatusEnum;
import com.aco.party.model.po.Posts;
import com.aco.party.model.po.Terms;
import com.aco.party.model.vo.PostsParam;
import com.aco.party.model.vo.PostsVo;
import com.aco.party.model.vo.TermsVo;
import com.aco.party.model.vo.common.DataGridEntry;
import com.aco.party.model.vo.common.Page;
import com.aco.party.model.vo.common.PageParam;
import com.aco.party.model.vo.common.Response;
import com.aco.party.service.system.PostsService;
import com.aco.party.service.system.MetaService;
import com.aco.party.service.system.TermsService;
import com.aco.party.service.system.VisitService;
import com.aco.party.web.command.system.EditPostsCommand;
import com.aco.party.web.validator.system.EditPostsValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

import static com.aco.party.util.WebModelUtil.getBasePath;

/**
 * Created by flying on 3/10/2016 0010.
 */
@Controller
@RequestMapping("/system")
public class ManagePostsController extends BaseController {
    Logger logger = LoggerFactory.getLogger(ManagePostsController.class);

    @Resource
    private PostsService postsService;

    @Resource
    private MetaService metaService;

    @Resource
    private TermsService termsService;

    private EditPostsValidator validator = new EditPostsValidator();

    private final String REDIRECTEDIT = "redirect:edit";

    @RequestMapping(value = {"/posts", "/posts/list"}, method = RequestMethod.GET)
    public String showManagePage(HttpServletResponse response) {
        return "system/managePostess";
    }

    @RequestMapping(value = "posts/list", method = RequestMethod.POST)
    @ResponseBody
    public Page
            <PostsVo> getListJson(HttpServletRequest request, DataGridEntry entry,String keywords) {
        Page <PostsVo> page = new Page<>();
        entry.webParamConvert();
        PostsParam param = new PostsParam();
        param.setType(PostTypeEnum.普通.getValue());
        if(!StringUtils.isEmpty(keywords)) {
            param.setKeywords(keywords + "%");
        }
        param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue(),PostsStatusEnum.隐藏.getValue()));
        param.setOrderClause(" case when extra_2='是' then 1 else 0 end desc,create_time desc");
        List <PostsVo> list = postsService.getByPage(new PageParam(entry.getOffset(), entry.getLimit()),param);
        page.setTotal(postsService.getTotal(param));
        page.setRows(list);
        return page;
    }

    @RequestMapping(value = "/posts/edit", method = RequestMethod.GET)
    public String showEdit(HttpServletResponse response,@ModelAttribute EditPostsCommand command, Model model) {
        setAtt(model);
        if (command.getId() != null) {
            Posts po = postsService.getByPrimaryKey(command.getId());
            if (po != null)
                command.toCommand(po);
            else
                model.addAttribute("no_obj", true);
            if(!StringUtils.isEmpty(command.getPostContent()) && command.getPostContent().contains("${base}")){
                command.setPostContent(command.getPostContent().replace("${base}", getBasePath()));
            }
            if(StringUtils.isEmpty(command.getExtra4())){
                command.setExtra4("不显示");
            }
        }
        if(!StringUtils.isEmpty(command.getFrom()) && "moke".equals(command.getFrom())){
            model.addAttribute("type","moke");
        }
        return "system/editPosts";
    }

    @RequestMapping(value = "/posts/edit", method = RequestMethod.POST)
    public String edit(Model model, @ModelAttribute EditPostsCommand command, BindingResult errors) {
        validator.validate(command, errors);
        setAtt(model);
        if (!errors.hasErrors()) {
            Posts posts = new Posts();
                command.toPo(posts);
            postsService.update(posts);
            model.addAttribute("no_error",true);
        }

        if(!StringUtils.isEmpty(command.getFrom()) && "moke".equals(command.getFrom())){
            model.addAttribute("type","moke");
        }
        return "system/editPosts";
    }

    @RequestMapping(value = "/posts/add", method = RequestMethod.GET)
    public String showAdd(Model model,@ModelAttribute EditPostsCommand command) {
        setAtt(model);
        command.setPostStatus(PostsStatusEnum.显示.getValue());
        command.setPostType(PostTypeEnum.普通.getValue());
        command.setPostTerm(172L);
        command.setExtra4("不显示");
        return "system/editPosts";
    }

    @RequestMapping(value = "/posts/add", method = RequestMethod.POST)
    public String add(Model model, @ModelAttribute EditPostsCommand command, BindingResult errors,RedirectAttributes attributes) {
        validator.validate(command, errors);
        setAtt(model);
        if (errors.hasErrors()) {
            return "system/editPosts";
        }
        Posts posts = new Posts();
        command.toPo(posts);
        posts.setPostAuthor(getCurrentUser().getId());
        postsService.add(posts);
        attributes.addAttribute("id", posts.getId());
        attributes.addFlashAttribute("no_error", true);
        return REDIRECTEDIT;
    }

    @RequestMapping(value = "/posts/delete",method = RequestMethod.POST)
    @ResponseBody
    public Response del(@RequestParam(required = true) Long id){
        logger.info("删除：" + id);
        postsService.delete(id);
        return new Response();
    }

    private void setAtt(Model model){
        List<TermsVo> termses = termsService.getByPage(null);
        model.addAttribute("terms", termses);
    }

    @RequestMapping(value = "/posts/up",method = RequestMethod.POST)
    @ResponseBody
    public Response up(@RequestParam(required = true) Long id,Integer isUp){
        Posts posts = postsService.getByPrimaryKey(id);
        if(posts != null){
            Posts temp = new Posts();
            temp.setId(posts.getId());
            if(isUp != null && isUp == 1)
                temp.setExtra2("是");
            else
                temp.setExtra2("否");
            temp.setExtra1(getCurrentUser().getUsername());
            postsService.update(temp);
        }
        return new Response();
    }

    @RequestMapping(value = {"/posts/verifyList"}, method = RequestMethod.GET)
    public String showAuthorPostsPage(HttpServletResponse response) {
        return "system/auditAuthorPosts";
    }

    @RequestMapping(value = "posts/verifyList", method = RequestMethod.POST)
    @ResponseBody
    public Page<PostsVo> getAuthorPosts(HttpServletRequest request, DataGridEntry entry,PostsParam param) {
        Page <PostsVo> page = new Page<>();
        entry.webParamConvert();
        param.setType(PostTypeEnum.魔客.getValue());
        List <PostsVo> list = postsService.getByPage(new PageParam(entry.getOffset(), entry.getLimit()),param);
        page.setTotal(postsService.getTotal(param));
        page.setRows(list);
        return page;
    }

    @RequestMapping(value = "/posts/verify",method = RequestMethod.POST)
    @ResponseBody
    public Response postsVerify(Long id,Long confirm){
        Posts posts = new Posts();
        posts.setId(id);
        if(confirm == 1){
            //同意
            posts.setPostStatus(PostsStatusEnum.审核通过.getValue());
            posts.setExtra1(getCurrentUser().getUsername());
        }else{
            //拒绝
            posts.setPostStatus(PostsStatusEnum.审核不通过.getValue());
            posts.setExtra1(getCurrentUser().getUsername());
        }
        postsService.update(posts);
        return new Response();
    }


    @RequestMapping(value = {"/posts/addAuthorPosts"}, method = RequestMethod.GET)
    public String showAddAuthorPostsPage(Model model,@ModelAttribute EditPostsCommand command,HttpServletResponse response) {
        if(!StringUtils.isEmpty(command.getFrom()) && "moke".equals(command.getFrom())){
            model.addAttribute("type","moke");
        }
        command.setPostType(PostTypeEnum.魔客.getValue());
        command.setPostStatus(PostsStatusEnum.审核通过.getValue());
        return "system/editPosts";
    }

    @RequestMapping(value = "posts/addAuthorPosts", method = RequestMethod.POST)
    public String addAuthorPosts(Model model, @ModelAttribute EditPostsCommand command, BindingResult errors,RedirectAttributes attributes) {
        validator.validate(command, errors);
        model.addAttribute("type","moke");
        if (errors.hasErrors()) {
            return "system/editPosts";
        }
        Posts posts = new Posts();
        command.toPo(posts);
        posts.setPostAuthor(getCurrentUser().getId());
        posts.setPostType(PostTypeEnum.魔客.getValue());
        posts.setExtra1(getCurrentUser().getUsername());
        postsService.add(posts);
        attributes.addAttribute("id",posts.getId());
        attributes.addFlashAttribute("no_error",true);
        return REDIRECTEDIT;
    }
}
